# -*- coding: utf-8 -*-
from time import sleep

from celery.result import AsyncResult
from celery import states

from project.task import sleep_task
import logging

logger = logging.getLogger(__name__)


def run_test():
    async_result1: AsyncResult = sleep_task.delay('task_name1')
    logger.info(f'async_result1.state:{async_result1.state}')

    async_result2 = sleep_task.delay('task_name2')
    logger.info(f'async_result2.state:{async_result2.state}')

    async_result3 = sleep_task.delay('task_name3')
    logger.info(f'async_result3.state:{async_result3.state}')

    async_result4 = sleep_task.delay('task_name4')
    logger.info(f'async_result4.state:{async_result4.state}')
    logger.info(f'sleep 11s, stop task ')
    sleep(11)
    logger.info('-'*27)
    logger.info(f'async_result1.state:{async_result1.state}')
    if async_result1.state != states.STARTED:
        async_result1.revoke(terminate=True, signal='SIGTERM')  # 正在执行的任务无法终止
        logger.info(f'async_result1.state:{async_result1.state}')
    logger.info(f'async_result2.state:{async_result2.state}')
    async_result2.revoke(terminate=True, signal='SIGTERM')  # 还未执行的任务可以终止
    logger.info(f'async_result2.state:{async_result2.state}')
    logger.info(f'async_result3.state:{async_result3.state}')
    async_result3.revoke(terminate=True, signal='SIGTERM')  # 还未执行的任务可以终止
    logger.info(f'async_result3.state:{async_result3.state}')
    i = 60
    while i > 0:
        logger.info(f'async_result1.state:{async_result1.state}')
        logger.info(f'async_result2.state:{async_result2.state}')
        logger.info(f'async_result3.state:{async_result3.state}')
        logger.info(f'async_result4.state:{async_result4.state}')
        sleep(1)
        i = i- 1
        logger.info('-'*27)
        pass
    pass


if __name__ == '__main__':
    while True:
        run_test()
        logger.info(f'sleep 10s, send task ')
        sleep(60)